package com.atguigu.eduservice.service.impl;

import com.alibaba.excel.EasyExcel;
import com.atguigu.eduservice.entity.EduSubject;
import com.atguigu.eduservice.entity.excel.SubjectData;
import com.atguigu.eduservice.entity.subject.OneSubject;
import com.atguigu.eduservice.entity.subject.TwoSubject;
import com.atguigu.eduservice.listener.SubjectExcelListener;
import com.atguigu.eduservice.mapper.EduSubjectMapper;
import com.atguigu.eduservice.service.EduSubjectService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 课程科目 服务实现类
 * </p>
 *
 * @author 陈烨庆
 * @since 2022-01-22
 */
@Service
public class EduSubjectServiceImpl extends ServiceImpl<EduSubjectMapper, EduSubject> implements EduSubjectService {

    /**
     * 添加课程分类
     *
     * @param file
     */
    @Override
    public void saveSubject(MultipartFile file, EduSubjectService subjectService) {
        try {
            EasyExcel.read(file.getInputStream(), SubjectData.class, new SubjectExcelListener(subjectService)).sheet().doRead();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    @Override
    public List<OneSubject> getAllSubject() {
        // 查询所有一级分类
        QueryWrapper<EduSubject> oneSubjectwrapper = new QueryWrapper<>();
        oneSubjectwrapper.eq("parent_id", "0");
        List<EduSubject> eduOneSubjects = baseMapper.selectList(oneSubjectwrapper);

        // 查询所有二级分类
        QueryWrapper<EduSubject> twoSubjectwrapper = new QueryWrapper<>();
        twoSubjectwrapper.ne("parent_id", "0");
        List<EduSubject> eduTwoSubjects = baseMapper.selectList(twoSubjectwrapper);

        // 封装成前端需要的格式
        ArrayList<OneSubject> finalSubjects = new ArrayList<>();

        // 遍历一级分类
        for (EduSubject eduOneSubject : eduOneSubjects) {
            OneSubject oneSubject = new OneSubject();
            BeanUtils.copyProperties(eduOneSubject, oneSubject);

            // 遍历二级分类
            List<TwoSubject> twoSubjects = oneSubject.getChildren();
            for (EduSubject eduTwoSubject : eduTwoSubjects) {
                if (eduOneSubject.getId().equals(eduTwoSubject.getParentId())) {
                    TwoSubject twoSubject = new TwoSubject();
                    BeanUtils.copyProperties(eduTwoSubject, twoSubject);
                    twoSubjects.add(twoSubject);
                }
            }
            oneSubject.setChildren(twoSubjects);


            finalSubjects.add(oneSubject);
        }


        return finalSubjects;
    }
}
